/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-07-10
*/
package com.rzico.basics.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Receiver;
import com.rzico.basics.entity.Shop;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.ReceiverService;
import com.rzico.basics.service.ShopService;
import com.rzico.core.entity.SysEmployee;
import com.rzico.core.service.SysEmployeeService;
import com.rzico.entity.Filter;
import com.rzico.entity.Pageable;
import com.rzico.entity.PageResult;
import com.rzico.basics.entity.MapLine;
import com.rzico.basics.service.MapLineService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.Api;
import com.rzico.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;

/**
 * 送货线路控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-07-10
 */
@Api(description = "送货线路接口")
@RestController
@RequestMapping("/admin/mapLine")
public class MapLineAdminController extends BaseController {

    @Autowired
    private MapLineService mapLineService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private ReceiverService receiverService;

    @Autowired
    private SysEmployeeService sysEmployeeService;

    /**
     * 分页查询送货线路
     *
     * @return
    */
    @ApiOperation("分页查询送货线路")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "shopId", value = "归属门店", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "线路名称", dataType = "String", paramType = "query")
    })
    public CommResult<MapLine> list(Long shopId ,String name, Pageable pageable) {

        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);

        if (shopId!=null){
           params.put("shopId", shopId);
        }

        if (name!=null){
            params.put("name", name);
        }

        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<MapLine> list = mapLineService.selectList(params);
        PageResult<MapLine> pageResult = new PageResult<MapLine>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     * 查询单条送货线路
     *
     * @return
    */

    @ApiOperation("查询单条送货线路")
    @GetMapping("/find/{id}")
    public CommResult<MapLine> find(@PathVariable String id) {

        MapLine result = mapLineService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("mapLine",result);

        Shop shop = shopService.findById(result.getShopId());

        if (shop!=null) {
            data.put("shopName",shop.getName());
        } else {
            data.put("shopName","无");
        }

        if (result.getShippingEmployeeId()!=null) {

            SysEmployee sysEmployee = sysEmployeeService.findById(result.getShippingEmployeeId());

            if (sysEmployee != null) {
                data.put("shippingEmployeeName", sysEmployee.getName());
            } else {
                data.put("shippingEmployeeName", "无");
            }

        }
        return CommResult.success(data);

    }

    /**
     * 保存送货线路
     *
     * @param mapLine
     * @return
     */
    @ApiOperation("保存送货线路")
    @PostMapping("/save")
    public CommResult<MapLine> save(@RequestBody MapLine mapLine) {

        Enterprise enterprise = enterpriseService.getCurrent();
        mapLine.setEnterpriseId(enterprise.getId());

        mapLine.setCreateDate(new Date());

        int affectCount = mapLineService.save(mapLine);
        if (affectCount <= 0) {
            return CommResult.error();
        }
        MapLine result = mapLineService.findById(mapLine.getId());
        return CommResult.success(result);

    }


    /**
     * 批量删除送货线路
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除送货线路", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除送货线路,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<MapLine> del(@PathVariable String ids) {

        mapLineService.deleteByIds(ids.split(","));
        return CommResult.success();
    }

    /**
     * 更新送货线路
     *
     * @param mapLine
     * @return
     */
    @Log(desc = "更新送货线路", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新送货线路")
    @PostMapping("/update")
    public CommResult<MapLine> update(@RequestBody MapLine mapLine) {
        int affectCount = mapLineService.update(mapLine);
        if (affectCount <= 0){
            return CommResult.error();
        }
        MapLine result = mapLineService.findById(mapLine.getId());
        return CommResult.success(result);
    }

    /**
     * 根据位置，分配获取送货线路
     *
     * @return
     */
    @ApiOperation("根据位置，分配获取送货线路")
    @PostMapping("/LBSLocation")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lat", value = "lat", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "lng", value = "lng", dataType = "String", paramType = "query")
    })
    public CommResult<MapLine> LBSLocation(Double lat,Double lng) {

        Enterprise enterprise = enterpriseService.getCurrent();
        MapLine result = mapLineService.findByPoint(enterprise,null,lat,lng);
        return CommResult.success(result);

    }

    /**
     * 根据收货地址，分配获取送货线路
     *
     * @return
     */
    @ApiOperation("根据收货地址，分配获取送货线路")
    @PostMapping("/receiverLocation")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "receiverId", value = "收货地址ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "shopId", value = "指定门店", dataType = "String", paramType = "query")
    })
    public CommResult<MapLine> receiverLocation(Long receiverId,Long shopId) {

        Receiver receiver = receiverService.findById(receiverId);
        if (receiver==null) {
            return CommResult.success();
        }

        Enterprise enterprise = enterpriseService.getCurrent();
        MapLine result = mapLineService.findByPoint(enterprise,shopId,receiver.getLat(),receiver.getLng());
        if (result!=null) {

            Map<String,Object> data = new HashMap<>();
            data.put("mapLine",result);

            Shop shop = shopService.findById(result.getShopId());
            if (shop!=null) {
                data.put("shopName",shop.getName());
            } else {
                data.put("shopName","无");
            }

            if (result.getShippingEmployeeId()!=null && !"".equals(result.getShippingEmployeeId())) {
                SysEmployee sysEmployee = sysEmployeeService.findById(result.getShippingEmployeeId());
                if (sysEmployee != null) {
                    data.put("shippingEmployeeName", sysEmployee.getName());
                } else {
                    data.put("shippingEmployeeName", "无");
                }
            }

            return CommResult.success(data);

        } else {
            return CommResult.success();
        }

    }


}
